package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备Service业务层处理
 *
 * @author alexis
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        QueryProductListRequest request = new QueryProductListRequest();
        request.setPageSize(100);
        request.setCurrentPage(1);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        // 调用第三方查询产品列表
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }

        // 判断，如果数据为空，则中断请求
        if (!response.getBody().success) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }

        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.body.data.list.productInfo;

        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, JSON.toJSONString(productInfo));


    }

    /**
     * 获取产品列表
     */
    @Override
    public List<ProductVo> getAllProduct() {
        String result = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);

        List<ProductVo> list = JSONUtil.toList(result, ProductVo.class);
        return list;
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1.判断设备名称是否重复
        Long count = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));

        //2.如果重复,结束流程
        if (count > 0) {
            throw new BaseException("设备名称重复,请重新输入");
        }

        //3.如果设备名称不重复,则进行注册流程,保存设备到iot平台
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //4.判断保存到iot平台是否成功,判断位置类型是否为0,如果是0,是随身设备,设置物理类型为-1
        if (!response.getBody().getSuccess()) {
            throw new BaseException("调用IOT设备注册失败");
        }

        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }

        //5.补全新增时返回的iot_id到设备对象中
        String iotId = response.getBody().getData().getIotId();
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(iotId);

        //6.保存设备到数据库
        try {
            int result = deviceMapper.insert(device);
            if (result == 0) {
                deleteIOTDevice(deviceDto, iotId);
                throw new BaseException("该老人已绑定该产品,请重新选择");
            }
        } catch (Exception e) {
            deleteIOTDevice(deviceDto, iotId);
            throw new BaseException("该老人已绑定该产品,请重新选择");
        }


    }

    /**
     * 查询设备详情
     *
     * @param deviceDto
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotId(deviceDto.getIotId());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setProductKey(deviceDto.getProductKey());

        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备，调用失败");
        }

        if (!response.getBody().getSuccess()) {
            throw new BaseException("物联网接口 - 查询设备，调用失败");
        }

        DeviceVo deviceVo = BeanUtil.toBean(response.getBody().getData(), DeviceVo.class);

        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));

        BeanUtil.copyProperties(device, deviceVo);

        return deviceVo;
    }

    /**
     * 查询物模型数据
     *
     * @param request
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }

        if (!response.getBody().success){
            throw new BaseException("物联网接口 - 查询物模型数据，调用失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询设备属性
     *
     * @param request
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性状态，调用失败");
        }

        if (!response.getBody().success){
            throw new BaseException("物联网接口 - 查询设备属性状态，调用失败");
        }

        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 修改设备
     *
     * @param device
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editDevice(Device device) {
        int i = deviceMapper.updateDevice(device);

        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> nicknameInfos = new ArrayList<>();

        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        nicknameInfo.setDeviceName(device.getDeviceName());
        nicknameInfo.setNickname(device.getNickname());
        nicknameInfo.setProductKey(device.getProductKey());

        nicknameInfos.add(nicknameInfo);

        request.setDeviceNicknameInfo(nicknameInfos);

        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if(!response.getBody().getSuccess()){
            throw new RuntimeException("更新设备失败");
        }
        return i;
    }

    /**
     * 删除设备
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(DeleteDeviceRequest request) {
        int result = deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, request.getIotId()));

        if (result == 0){
            throw new BaseException("该设备不存在");
        }

        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.getBody().getSuccess()){
            throw new RuntimeException("删除设备失败");
        }
    }

    private void deleteIOTDevice(DeviceDto device, String iotId) {
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.setDeviceName(device.getDeviceName());
        deleteDeviceRequest.setProductKey(device.getProductKey());
        deleteDeviceRequest.setIotId(iotId);
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
